# Filters added to this controller will be run for all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
  before_filter :authenticate
  before_filter :authorize_admin
  
  EXTERNAL_GROUP = "Outfit Member"

  def authenticate
    authenticate_debug
    if(session[:user_valid] == true) 
      return true
    end
    
    retval = true
    if(cookies[:SMFUser].nil?)
      redirect_to "http://www.thephoenixcompany.org/SMF/index.php?action=login"
      retval = false
    elsif(user_not_defined?)
      retval = create_account
    else
      # Double check that external authenticity is still valid
      retval = authenticates_externally?
      if(retval == true)
        # cache the authentication so that we don't have to do it all of the time
        session[:user_valid] = true
      end
    end
    return retval
  end
  
  def authorize_admin
    member = Member.find(session[:member_id])
    if member.is_admin?
      flash[:notice] = 'Admin access'
      return true
    end
    flash[:notice] = 'You do not have permission to view that page'
    redirect_to :controller => 'command', :action => 'index'
    return false
  end
  
  def authenticate_debug
    if(ENV["RAILS_ENV"] == "development")
      session[:user_valid] = false
      cookies[:SMFUser] = "Cord"
    end
  end
  
  def user_not_defined?
    member = Member.find_by_smf_name(cookies[:SMFUser])
    return member.nil?
  end
  
  def authenticates_externally?
    smf_member = SMFMember.find_by_memberName(cookies[:SMFUser])
    if(smf_member.nil?)
      redirect_to "http://www.thephoenixcompany.org/SMF/index.php?action=login"
      return false
    end
    smf_groups = smf_member.smf_groups
    for id_group in smf_groups
      group = SMFMembergroup.find_by_ID_GROUP(id_group)
      if(group.nil? == false and group.groupName == EXTERNAL_GROUP)
        return true
      end
    end 
    return false
  end
  
  def create_account   
    if authenticates_externally? == false
      return false
    end
    smf_member = SMFMember.find_by_memberName(cookies[:SMFUser])
    member = Member.new({:name => smf_member.realName, 
                         :member_status_id => MemberStatus.find_by_name('Active'),
                         :smf_name => smf_member.memberName})
    if member.save
      flash[:notice] = 'As this is your first visit, an account has been created for you.  
                        Contact a Company officer if you require additional access within the Mission Planner.'
      redirect_to :controller => 'command', :action => 'index'
    end
    return true
  end
end
